package com.topisv.tms.web.pickCar;

import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.pickCar.PickCar;
import com.topisv.tms.entity.pickCar.PickCarStock;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.repository.pickCar.PickCarDao;
import com.topisv.tms.repository.work.WorkTaskDao;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.pickCar.PickCarService;
import com.topisv.tms.service.pickCar.PickCarStockService;
import com.topisv.tms.utils.JsonUtil;
import com.topisv.tms.web.base.BaseController;

/**
 * 拣货车_control
 * @author ch
 */
@Controller
@RequestMapping({ "/pickCar" })
public class PickCarController extends BaseController{

	private static final Logger logger = LoggerFactory.getLogger(PickCarController.class);

	@Autowired
	private PickCarService pickCarService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private PickCarStockService pickCarStockService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private PickCarDao pickCarDao;
	@Autowired
	private WorkTaskDao workTaskDao;
	
	
	/**
	 * 导向拣货车管理页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "v2_toPickCarMgr")
	public String toPickCarMgr(ServletRequest request,HttpServletResponse response,Model model){
		
		//查找商户组
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		User user=this.accountService.findUserByJobuuid(curUser.jobuuid);
		List<Customers> customerList;
		if(user.getUserType().equals("paiu")){ //派友用户
		    customerList=this.customersService.findAll();
			model.addAttribute("customerList",customerList);
		}else if(user.getUserType().equals("customer")){ //商家用户
			customerList=new ArrayList<Customers>();
			String customerCode=curUser.customerCode;
		    Customers customer=this.customersService.findByCustomerCode(customerCode);
			customerList.add(customer);
			model.addAttribute("customerList",customerList);
			model.addAttribute("customer", customer); 
		}
	    
		return "pickCar/pickCarMgr";
	}
	
	//查询拣货车
	@RequestMapping(value = "v2_queryPickCar")
	public String queryPickCar(Model model, ServletRequest request) {
		try {
			
			//查找商户组
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			User user=this.accountService.findUserByJobuuid(curUser.jobuuid);
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			fillSelectValue(model, param.get("customerCode").toString());
			List<Customers> customerList;
			if(user.getUserType().equals("paiu")){ //派友用户
			    customerList=this.customersService.findAll();
				model.addAttribute("customerList",customerList);
			}else if(user.getUserType().equals("customer")){ //商家用户
				customerList=new ArrayList<Customers>();
				String customerCode=curUser.customerCode;
			    Customers customer=this.customersService.findByCustomerCode(customerCode);
				customerList.add(customer);
				model.addAttribute("customerList",customerList);
			}
			
			List<PickCar> pickCarList = this.pickCarService.loadPickCarByParam(param);
			model.addAttribute("pickCarList", pickCarList);
			  
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "pickCar/pickCarMgr";
	}
	
	/**
	 * 创建拣货车
	 * @param bill
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "ajaxCreatePickCar")
	@ResponseBody
	public String ajaxCreatePickCar(HttpServletResponse response,ServletRequest request) {
		try {
			
			String carName=request.getParameter("carName");
			String customerCode=request.getParameter("customerCode");
			String warehouseCode=request.getParameter("warehouseCode");
			Integer stockNum=Integer.valueOf(request.getParameter("stockNum"));
			
			
			PickCar pickCar=new PickCar();
			
		    Random r=new Random();
			DecimalFormat df=new DecimalFormat("000");
			String carCode=null;
			while(true){
				String temp=df.format(r.nextInt(999));
				carCode="C"+warehouseCode+temp;
				PickCar tempCar=this.pickCarService.loadCarByCode(carCode);
				if(tempCar==null){
					break;
				}
			}
			pickCar.setCarCode(carCode);
		    
			pickCar.setCarName(carName);
			pickCar.setCustomerCode(customerCode);
			pickCar.setWarehouseCode(warehouseCode);
			pickCar.setStockNum(stockNum);
			
			this.pickCarService.save(pickCar);
			
			return "true";
			
		} catch (Exception e) {
			
			logger.error("error",e);
			return "false";
		}
	}
	
	/**
	 * 删除拣货车
	 * @param pickCarId 拣货车ID
	 * @return
	 */
	@RequestMapping(value = "ajaxDeletePickCar")
	@ResponseBody
	public String ajaxDeletePickCar(HttpServletResponse response,ServletRequest request) {
		try {
			Long pickCarId=Long.valueOf(request.getParameter("pickCarId"));
			this.pickCarService.delete(pickCarId);
			return "true";
			
		} catch (Exception e) {
			
			logger.error("error",e);
			return "false";
		}
	}
	
	/**
	 * 释放拣货车
	 * @param pickCarId 拣货车ID
	 * @return
	 */
	@RequestMapping(value = "ajaxFree")
	@ResponseBody
	public void ajaxFree(HttpServletResponse response,ServletRequest request) {
	    PrintWriter out=null;
        JSONObject json=null;
        ShiroUser user = getShiroUser();
	    try {
	        out = response.getWriter();
            json = new JSONObject();
			Long pickCarId=Long.valueOf(request.getParameter("pickCarId"));
			PickCar car=this.pickCarDao.findOne(pickCarId);
			WorkTask task =  this.workTaskDao.loadTaskByTaskCode(car.getTaskCode());
			if(task == null || task.getStatus().equals("7") || task.getStatus().equals("8") 
			    || task.getStatus().equals("9")){
	            this.pickCarService.free(pickCarId);
	            json.put("status", "success");
	            logger.info("------开始释放拣货车------");
	            logger.info("释放人:" + user.getRealname() + " " + "拣货车编码:" + car.getCarCode() + " " + 
	               "释放时间:" + new Date());
			}else{
			    json.put("status", "notFree");
			}
			
		} catch (Exception e) {
			
			logger.error("error",e);
			json.put("status", "fail");
		} finally{
		    out.print(json);
		}
	}
	
	/**
	 * 查询拣货车详细信息
	 * @param pickCarId 拣货车ID
	 * @return
	 */
	@RequestMapping(value = "ajaxLoadPickCarDetail")
	public void ajaxLoadPickCarDetail(HttpServletResponse response,ServletRequest request) {
		try {
			Long pickCarId=Long.valueOf(request.getParameter("pickCarId"));
			PickCar pickCar=this.pickCarService.loadPickCarById(pickCarId);
			List<PickCarStock> stockList=this.pickCarStockService.loadStockByCarId(pickCar.getId());
			
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("pickCar", pickCar);
			map.put("stockList", stockList);
			String json = JsonUtil.getObjectString(map);
			PrintWriter out;
			out = response.getWriter();
			out.print(json);
			
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
	}
	
}